package in.iqing.control.api.volley;

import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import in.iqing.control.helper.LogHelper;


/**
 * Created by Zuoshu on 2014/12/11.
 */
public class ExtendStringRequest extends StringRequest implements Response.Listener<String>, Response.ErrorListener {

    private static final String TAG = "ExtendStringRequest";
    public static final int TIME_OUT_MS_LONG = 8000;
    private String userAgent;
    private RetryPolicy retryPolicy;
    private WeakReference<Response.Listener<String>> weakSuccessListener;
    private WeakReference<Response.ErrorListener> weakErrorListener;

    public ExtendStringRequest(String userAgent, int method, int timeout, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(method, url, listener, errorListener);
        this.userAgent = userAgent;
        retryPolicy = new DefaultRetryPolicy(timeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        setRetryPolicy(retryPolicy);
        weakSuccessListener = new WeakReference<Response.Listener<String>>(listener);
        weakErrorListener = new WeakReference<Response.ErrorListener>(errorListener);
    }

    public ExtendStringRequest(String userAgent, int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        this(userAgent, method, DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, url, listener, errorListener);
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        if (!TextUtils.isEmpty(userAgent)) {
            headers.put("User-agent", userAgent);
        }
        return headers;
    }

    @Override
    public void onResponse(String s) {
        Response.Listener listener = weakSuccessListener.get();
        if (listener != null) {
            listener.onResponse(s);
        } else {
            LogHelper.warn(TAG, "success listener went away in response");
        }
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        Response.ErrorListener listener = weakErrorListener.get();
        if (listener != null) {
            listener.onErrorResponse(volleyError);
        } else {
            LogHelper.warn(TAG, "error listener went away in response");
        }

    }
}
